'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Admin Template' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || 9528 // dev port

// 认知：
// 1. 如果是开发环境，没必要用过cdn的资源（要花钱）
//    访问本地node_modules的即可
// 2. 如果是生产环境，才需要用cdn的资源（给客户用）
//    访问cdn的

let externals = {} // 需要排除的包对象，默认为空
let cdn = { css: [], js: [] } // 需要加载的cdn服务，默认为空

const isProduction = process.env.NODE_ENV === 'production'

// 判断是否是生产环境
if (isProduction) {
  externals = {
    // key(要排除的包名), value(引入的CDN包的全局变量名)
    'element-ui': 'ELEMENT',
    'xlsx': 'XLSX',
    'moment': 'moment'
  }
  cdn = {
    css: [
      'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // element-ui css 样式表
    ],
    js: [
      // vue must at first!
      'https://unpkg.com/element-ui/lib/index.js', // element-ui js
      'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/jszip.min.js',
      'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/xlsx.full.min.js',
      'https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js'
    ]
  }
}
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // 以 /api 开头的路径请求, 认为需要走代理
      // 原本:   http://localhost:8888/api/sys/login
      // 代理后: http://ihrm-java.itheima.net/api/sys/login
      // 将本机地址, 会替换成代理的地址, 进行请求
      // '/api': {
      //   target: 'http://103.47.83.172:3000'
      // },

      '/api': {
        target: 'http://124.223.73.204:3000'
      }

      // 注意这里的路径要和环境变量中的基地址路径统一
      // '/prod-api': {
      //   target: 'http://ihrm.itheima.net'
      // }

      // '/api': {
      //   target: 'http://localhost:3000'
      // }
    }
  },
  // import xxx from '包名'
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    // 这里的name变量, 可以在index.html中被获取到, 用于设置正确的标题
    name: name,
    // 设置排除项，这些包不会从node_modules中加载，而是从三方包加载
    externals: externals,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // 注入cdn变量 (打包时会执行)
    config.plugin('html').tap(args => {
      args[0].cdn = cdn // 配置cdn给插件
      return args
    })

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  }
}

// 跨域配置补充说明:
// -------------------- 一. 需要请求的地址 - 直接有标识 ------------------
// 需要请求的地址:
// 1. http://www.baidu.com/api/login
// 2. http://www.baidu.com/api/register

// 页面请求1: http://localhost:8888/api/login
// 页面请求2: http://localhost:8888/api/register

// 如何配置:
// proxy: {
//   '/api': {
//     target: 'http://www.baidu.com'
//   }
// }

// 将 /api 前面的基地址 进行替换, 替换成 target 地址

// -------------------- 二. 需要请求的地址 - 没有标识 ------------------
// 需要请求的地址:
// 1. http://www.baidu.com/login
// 2. http://www.baidu.com/register

// 页面请求1: http://localhost:8888/api/login   请求时额外新增了一个标识
// 页面请求2: http://localhost:8888/api/register

// 如何配置:
// proxy: {
//   '/api': {
//     target: 'http://www.baidu.com',
//     // 路径重写, 去掉额外添加的 /api 标识, 替换成 ''
//     pathRewrite: {
//       '^/api': ''
//     }
//   }
// }

// (1) 将target地址, 去替换 http://localhost:8888 基地址
// (2) pathRewrite, 将额外多余的 /api 进行覆盖移除
